package com.songlanyun.modules.returnaddress.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.common.validator.group.AddGroup;
import com.songlanyun.common.validator.group.UpdateGroup;
import com.songlanyun.modules.returnaddress.dao.ReturnAddressDao;
import com.songlanyun.modules.returnaddress.entity.ReturnAddress;
import com.songlanyun.modules.returnaddress.model.dto.ReturnAddressDTO;
import com.songlanyun.modules.returnaddress.service.ReturnAddressService;
import com.songlanyun.modules.shop.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("shopReturnAddressService")
public class ReturnAddressServiceImpl extends ServiceImpl<ReturnAddressDao, ReturnAddress> implements ReturnAddressService {

    @Autowired
    private ShopService shopService;


    public ReturnAddress create(ReturnAddress entity) {
        ValidatorUtils.validateEntity(entity,AddGroup.class);
        this.baseMapper.insert(entity);
        return entity;
    }


    public ReturnAddress modify(ReturnAddress entity) {
        ValidatorUtils.validateEntity(entity,UpdateGroup.class);
        this.baseMapper.updateById(entity);
        return entity;
    }

    /**
     * 商家设置自家店铺的收货地址
     * @param shopId
     * @param dto
     * @return
     */
    @Override
    public ReturnAddress set(Long shopId, ReturnAddressDTO dto) {
        shopService.loadShopBy(shopId,true);
        ReturnAddress returnAddress = this.getReturnAddress(shopId);
        if(returnAddress==null)
        {
            ReturnAddress entity = new ReturnAddress();
            BeanUtils.copyProperties(dto,entity);
            entity.setShopId(shopId);
            this.create(entity);
            return entity;
        }
        else
        {
            Long id = returnAddress.getId();
            BeanUtils.copyProperties(dto,returnAddress);
            returnAddress.setShopId(shopId);
            returnAddress.setId(id);
            this.modify(returnAddress);
            return returnAddress;
        }
    }

    /**
     *  商家获取自家店铺的收货地址
     * @param shopId
     * @return
     */
    @Override
    public ReturnAddress getReturnAddress(Long shopId) {
        return this.baseMapper.selectOne(
                new LambdaQueryWrapper<ReturnAddress>().
                        eq(ReturnAddress::getShopId,shopId).last("limit 1")
        );
    }
}